//
//  EXFileManager.swift
//  Exchange
//
//  Created by rui on 2018/6/11.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class EXFileManager {

    
    enum Paths {
        case exTickPath
        case exRatePath
        case tradeCoinPath
        case coinCoinPath
        
        func path() -> String {
            let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last ?? ""
            var path = ""
            switch self {
            case .exTickPath:
                path = "my_extick.data"
            case .exRatePath:
                path = "my_rate.data"
            case .tradeCoinPath:
                path = "my_tcoin.data"
            case .coinCoinPath:
                path = "my_ccoin.data"
            }
            return "\(docPath)/\(path)"
        }
    }
    
    private let queue = DispatchQueue(label: "in.coningo.www.filenanager")
    
    static let `default` = EXFileManager()
    
    private init(){
        
    }
    @discardableResult
    func read(from path: EXFileManager.Paths) -> Data? {
        var data: Data?
        queue.sync {
            let filePath = path.path()
            if FileManager.default.fileExists(atPath: filePath) {
               data =  FileManager.default.contents(atPath: filePath)
            }
        }
        return data
    }
    
    func readAsync(form path: EXFileManager.Paths, completion:@escaping (Data?) -> Swift.Void) {
        queue.async {
            let filePath = path.path()
            if FileManager.default.fileExists(atPath: filePath) {
                let data = FileManager.default.contents(atPath: filePath)
                completion(data)
            }else {
                completion(nil)
            }
        }
    }
    @discardableResult
    func write(data: Data, to path: EXFileManager.Paths) -> Bool {
        var flag = false
        queue.sync {
            let filePath = path.path()
            if FileManager.default.fileExists(atPath: filePath) {
                try? FileManager.default.removeItem(atPath: filePath)
            }
            flag = FileManager.default.createFile(atPath: filePath, contents: data, attributes: nil)
        }
        return flag
    }
    
    func writeAsync(data: Data, to path: EXFileManager.Paths,completion:@escaping (Bool) -> Swift.Void) {
        queue.async {
            let filePath = path.path()
            if FileManager.default.fileExists(atPath: filePath) {
                try? FileManager.default.removeItem(atPath: filePath)
            }
            let flag = FileManager.default.createFile(atPath: filePath, contents: data, attributes: nil)
            completion(flag)
        }
    }

}
